package com.ck.company.controller;

import com.ck.company.service.CpDeviceGroupService;
import com.ck.constant.ClientConstant;
import com.ck.constant.DeviceGroupConstant;
import com.ck.constant.ResponseConstant;
import com.ck.core.BaseController;
import com.ck.exception.ControllerException;
import com.ck.model.common.DeviceGroup;
import com.ck.model.common.User;
import com.ck.model.common.sys.JsonResponse;
import com.ck.model.company.dto.CpDeviceGroupTreeListDTO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/deviceGroup")
public class CpDeviceGroupController extends BaseController{
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private CpDeviceGroupService deviceGroupService;
    /**
     *  终端分组列表
     */
    @ResponseBody
    @RequestMapping(value = "/listDeviceGroup")
    public Object listDeviceGroup(HttpServletRequest request) {
        try {
    		//获取用户信息
    		User user = getSessionUser(request);
    		if(user == null) {
    			return new ControllerException("用户名为空，请联系管理员");
    		}
            return deviceGroupService.listAllDeviceGroup(user.getCompanyCode());
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error("CpDeviceGroupController listDeviceGroup 终端分组列表失败：" + e.getMessage(),e);
            return new ControllerException("终端分组列表失败");
        }
    }


    /**
     *  保存终端分组
     */
    @ResponseBody
    @RequestMapping(value = "/saveDeviceGroup")
    public Object saveDeviceGroup(DeviceGroup deviceGroup, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
        String message = "";
        String groupName = deviceGroup.getGroupName();
        String groupCode = deviceGroup.getGroupCode();
        if (StringUtils.isBlank(groupName)) {
            message = message + "分组名不能为空";
        } else if (StringUtils.isBlank(groupCode)) {
            message = message + "分组码不能为空";
        }
        if (message.length() > 0) {
            return new ControllerException(message);
        }
        try {
            deviceGroupService.saveDeviceGroup(deviceGroup, user, getOperationIp(request));
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error("CpDeviceGroupController saveDeviceGroup 保存终端分组失败：" + e.getMessage(),e);
            return new ControllerException("保存终端分组失败:" + e.getMessage());
        }
        return "保存终端分组成功";
    }

    /**
     *  更新终端分组
     */
    @ResponseBody
    @RequestMapping(value = "updateDeviceGroup")
    public Object updateDeviceGroup(DeviceGroup deviceGroup, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
        String message = "";
        Long groupId = deviceGroup.getDeviceGroupId();
        String groupName = deviceGroup.getGroupName();
        String groupCode = deviceGroup.getGroupCode();
        if(groupId == null) {
            message = message + "终端分组id不能为空";
        } else if (StringUtils.isBlank(groupName)) {
            message = message + "分组名不能为空";
        } else if (StringUtils.isBlank(groupCode)) {
            message = message + "分组码不能为空";
        }
        if (message.length() > 0) {
            return new ControllerException(message);
        }
        try {
            deviceGroupService.updateDeviceGroup(deviceGroup, user, getOperationIp(request));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpDeviceGroupController updateDeviceGroup 更新终端分组失败：" + e.getMessage(),e);
            return new ControllerException("更新终端分组失败:" + e.getMessage());
        }
        return "更新终端分组成功";
    }

    /**
     *  删除终端分组
     */
    @ResponseBody
    @RequestMapping(value = "/deleteDeviceGroup")
    public Object deleteDeviceGroup(Long deviceGroupId, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
        if (deviceGroupId == null) {
            return new ControllerException("终端分组id不能为空");
        }
        try {
        	String companyCode = user.getCompanyCode();
            //检查终端分组是否有子分组
            List<DeviceGroup> deviceChildGroupList = deviceGroupService.listDeviceGroupByParentId(companyCode,deviceGroupId);
            if (!deviceChildGroupList.isEmpty()) {
                return new JsonResponse(ResponseConstant.CODE_FAIL,"删除终端分组失败,终端分组下有子分组");
            }
            DeviceGroup deviceGroup = deviceGroupService.getDeviceGroup(companyCode,deviceGroupId);
            if(deviceGroup == null) {
                return new JsonResponse(ResponseConstant.CODE_FAIL,"删除终端分组失败,终端分组不存在");
            }
            deviceGroupService.deleteDeviceGroup(deviceGroupId, deviceGroup.getGroupName(), deviceGroup.getDeviceGroupId(), user, getOperationIp(request));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpDeviceGroupController deleteDeviceGroup 删除终端分组失败：" + e.getMessage(),e);
            return new ControllerException("删除终端分组失败");
        }
        return "删除终端分组成功";
    }

    /**
     * 生成分组树形列表
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/listDeviceGroupTree")
    public Object deviceGroupTreeList(HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
        try {
            //查询所有菜单
            List<CpDeviceGroupTreeListDTO> allMenu = deviceGroupService.listAllDeviceGroupTree(user.getCompanyCode());
            //根节点
            List<CpDeviceGroupTreeListDTO> rootMenu = new ArrayList<CpDeviceGroupTreeListDTO>();

            for (CpDeviceGroupTreeListDTO nav : allMenu) {
                //父节点为null的，为根节点。
                if(nav.getPid() == null || "".equals(nav.getPid())){
                    rootMenu.add(nav);
                }
            }
            //为根菜单设置子菜单，getClild是递归调用的
            for (CpDeviceGroupTreeListDTO nav : rootMenu) {
                /* 获取根节点下的所有子节点 使用getChild方法*/
                List<CpDeviceGroupTreeListDTO> childList = getChild(nav.getDeviceGroupId(), allMenu);
                //给根节点设置子节点
                nav.setChildren(childList);
            }

            /**
             * 自创一个最高节点叫“全部分组”
             * 它是所有根节点的父节点
             */
            CpDeviceGroupTreeListDTO specialMenu = new CpDeviceGroupTreeListDTO();
            specialMenu.setLabel(DeviceGroupConstant.ALL_DEVICE_GROUP_NAME);
            specialMenu.setGroupCode(DeviceGroupConstant.ALL_DEVICE_GROUP_CODE);
            specialMenu.setDeviceGroupId(DeviceGroupConstant.ALL_DEVICE_GROUP_ID);
            specialMenu.setOpen(true);
            specialMenu.setChildren(rootMenu);

            //自创一个最高节点叫“未分组”,所有未分组的终端在该组
            CpDeviceGroupTreeListDTO noGroup = new CpDeviceGroupTreeListDTO();
            noGroup.setLabel(DeviceGroupConstant.NO_DEVICE_GROUP_NAME);
            noGroup.setGroupCode(DeviceGroupConstant.NO_DEVICE_GROUP_CODE);
            noGroup.setDeviceGroupId(DeviceGroupConstant.NO_DEVICE_GROUP_ID);
            noGroup.setOpen(false);

            // 返回给页面的树形列表
            List<CpDeviceGroupTreeListDTO> treeMenu = new ArrayList<CpDeviceGroupTreeListDTO>();
            treeMenu.add(specialMenu);
            treeMenu.add(noGroup);
            return treeMenu;
        } catch (Exception e) {
        	e.printStackTrace();
            logger.error("CpDeviceGroupController deviceGroupTreeList 终端分组列表失败：" + e.getMessage(),e);
            return new ControllerException("终端分组列表失败");
        }
    }

    /**
   * 获取子节点
   * @param id 父节点id
   * @param allMenu 所有菜单列表
   * @return 每个根节点下，所有子菜单列表
   */
    private List<CpDeviceGroupTreeListDTO> getChild(Long id,List<CpDeviceGroupTreeListDTO> allMenu){
        //子菜单
        List<CpDeviceGroupTreeListDTO> childList = new ArrayList<>();
        for (CpDeviceGroupTreeListDTO nav : allMenu) {
            /**
             * 遍历所有节点，将所有菜单的父id与传过来的根节点的id比较
             * 相等说明：为该根节点的子节点。
             */
            if(nav.getPid() != null && (id.toString()).equals(nav.getPid())){
                childList.add(nav);
            }
        }
        //递归
        for (CpDeviceGroupTreeListDTO nav : childList) {
            nav.setChildren(getChild(nav.getDeviceGroupId(), allMenu));
        }
        //如果节点下没有子节点，返回一个空List（递归退出）
        if(childList.size() == 0){
            return new ArrayList<>();
        }
        return childList;
    }

    /**
     * 移动终端到分组
     * @param deviceGroupId
     * @param deviceCodes
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/moveDeviceGroup")
    public Object moveDeviceGroup(Long deviceGroupId, String deviceCodes, HttpServletRequest request) {
		//获取用户信息
		User user = getSessionUser(request);
		if(user == null) {
			return new ControllerException("用户名为空，请联系管理员");
		}
        if(deviceGroupId == null && StringUtils.isBlank(deviceCodes)) {
            return new ControllerException(ClientConstant.MSG_PARAM_ERROR);
        }
        try {
            deviceGroupService.moveDeviceGroup(deviceGroupId, deviceCodes, user, getOperationIp(request));
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("CpDeviceGroupController moveDeviceGroup 移动终端到分组失败：" + e.getMessage(),e);
            return new ControllerException("移动终端到分组失败: " + e.getMessage());
        }
        return "";
    }
}
